/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
//  AppDelegate.m
//  HelloWorld
//
//  Created by ___FULLUSERNAME___ on ___DATE___.
//  Copyright ___ORGANIZATIONNAME___ ___YEAR___. All rights reserved.
//

#import "AppDelegate.h"
#import "MainViewController.h"
#import "BPush.h"
#import <Cordova/CDVPlugin.h>
#import <Cordova/UIDevice+Extensions.h>
#import "JSONKit.h"

#define NOTIFICATION_CDVPUSHJUMPPAGE @"noti_PushJumpPage"
#define SAVEPUSHMESSAGE @"saveReceivedPushMessage"
#define URL_UPDATEPUSHCONTENTANDUDID  @"http://192.168.2.222:8080/staff/user/setPushInfo"

@interface CustomNavigationController : UINavigationController

@end
@implementation CustomNavigationController

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return YES;
}
//ios6 以后
-(NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}

- (BOOL)shouldAutorotate{
    return YES;
}

@end

@interface AppDelegate ()<NSURLConnectionDataDelegate>

@end

@implementation AppDelegate

@synthesize window, viewController;

- (id)init
{
    /** If you need to do any extra app-specific initialization, you can do it here
     *  -jm
     **/
    NSHTTPCookieStorage* cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    
    [cookieStorage setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
    
    int cacheSizeMemory = 8 * 1024 * 1024; // 8MB
    int cacheSizeDisk = 32 * 1024 * 1024; // 32MB
#if __has_feature(objc_arc)
    NSURLCache* sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
#else
    NSURLCache* sharedCache = [[[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"] autorelease];
#endif
    [NSURLCache setSharedURLCache:sharedCache];
    
    self = [super init];
    return self;
}

#pragma mark UIApplicationDelegate implementation

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
    NSLog(@"applicationWillEnterForeground!");
}
/**
 * This is main kick off after the app inits, the views and Settings are setup here. (preferred - iOS4 and up)
 */
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    CGRect screenBounds = [[UIScreen mainScreen] bounds];
    
#if __has_feature(objc_arc)
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
#else
    self.window = [[[UIWindow alloc] initWithFrame:screenBounds] autorelease];
#endif
    self.window.autoresizesSubviews = YES;
    
    
    
#if __has_feature(objc_arc)
    self.viewController = [[MainViewController alloc] init];
    self.navigation = [[CustomNavigationController alloc] initWithRootViewController:self.viewController];
    self.navigation.navigationBarHidden = YES;
#else
    self.viewController = [[[MainViewController alloc] init] autorelease];
    
    self.navigation = [[[CustomNavigationController alloc] initWithRootViewController:self.viewController] autorelease];
#endif
    
    // Set your app's start page by setting the <content src='foo.html' /> tag in config.xml.
    // If necessary, uncomment the line below to override it.
    // self.viewController.startPage = @"index.html";
    
    // NOTE: To customize the view's frame size (which defaults to full screen), override
    // [self.viewController viewWillAppear:] in your view controller.
    
    // iOS8 下需要使用新的 API
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType myTypes = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:myTypes categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }else {
        UIRemoteNotificationType myTypes = UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound;
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:myTypes];
    }
    
#warning 上线 AppStore 时需要修改 pushMode
    // 在 App 启动时注册百度云推送服务，需要提供 Apikey
    [BPush registerChannel:launchOptions apiKey:@"d73OXfn1jnBNGZ9ZZ7VlK2D4" pushMode:BPushModeDevelopment withFirstAction:nil withSecondAction:nil withCategory:nil isDebug:YES];
    //    [BPush setupChannel:launchOptions];
    
    // 设置 BPush 的回调
    
    // App 是用户点击推送消息启动
    NSDictionary *userInfo = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    if (userInfo) {
        NSLog(@"从消息启动:%@",userInfo);
        [BPush handleNotification:userInfo];
    }
       [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    self.window.rootViewController = self.navigation;
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    // 打印到日志 textView 中
    NSLog(@"didReceiveRemoteNotification_fetchCompletionHandler: %@",userInfo);
    completionHandler(UIBackgroundFetchResultNewData);
    NSDictionary *contentDic = [userInfo objectForKey:@"content"];
    [[NSUserDefaults standardUserDefaults] setObject:contentDic forKey:SAVEPUSHMESSAGE];
    //判断是否是从后台点击消息推送到
    if (application.applicationState == UIApplicationStateActive) {
        NSLog(@"active");
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVEPUSHMESSAGE];
    }else if(application.applicationState == UIApplicationStateInactive){
        NSLog(@"Inactive");
        [[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_CDVPUSHJUMPPAGE object:nil userInfo:contentDic];
    }
}

// 在 iOS8 系统中，还需要添加这个方法。通过新的 API 注册推送服务
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
    
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSLog(@"test:%@",deviceToken);
    [BPush registerDeviceToken:deviceToken];
    [BPush bindChannelWithCompleteHandler:^(id result, NSError *error) {
        if (result) {
            
            NSDictionary *response_params = [result objectForKey:@"response_params"];
            NSString *userId = [response_params objectForKey:@"user_id"];
            NSString *channelId = [response_params objectForKey:@"channel_id"];
            //uuid
            UIDevice* device = [UIDevice currentDevice];
            NSString *uuid = [[NSString alloc]initWithString:[device uniqueAppInstanceIdentifier]];
            
            NSString *urlString = [NSString stringWithFormat:URL_UPDATEPUSHCONTENTANDUDID];
            NSURL *url = [NSURL URLWithString:urlString];
            //创建请求
            NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
            //创建参数字符串对象
            NSString *parmStr = [NSString stringWithFormat:@"udid=%@&channelId=%@&baiduUserId=%@&device_type=ios",uuid,channelId,userId];
            //将字符串转换为NSData对象
            NSData *postData = [parmStr dataUsingEncoding:NSUTF8StringEncoding];
            [request setHTTPBody:postData];
            [request setHTTPMethod:@"POST"];
            //创建异步连接（形式二）
            [NSURLConnection connectionWithRequest:request delegate:self];
        }
    }];
    
    NSString *additionStr = [[NSString stringWithFormat:@"Register use deviceToken : %@",deviceToken] stringByAppendingString:@"\n\n"];
    NSLog(@"Register use deviceToken : %@",additionStr);
    
}

// 当 DeviceToken 获取失败时，系统会回调此方法
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"DeviceToken 获取失败，原因：%@",error);
}

//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
//{
//    // App 收到推送的通知
//    [BPush handleNotification:userInfo];
//    NSString *additionStr = [NSString stringWithFormat:@"Received Remote Notification :\n%@",userInfo];
//    NSLog(@"%@",additionStr);
//}

// 服务器接收到请求时
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"response=%@",response);
}
// 当收到服务器返回的数据时触发, 返回的可能是资源片段
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"didReceiveData=%@",data);
    NSString *receivedStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [receivedStr objectFromJSONString];
    NSLog(@"dic == %@",dic);
}
// 当服务器返回所有数据时触发, 数据返回完毕
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"connectionDidFinishLoading");
}
// 请求数据失败时触发
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"didFailWithError==%s", __FUNCTION__);
}

// this happens while we are running ( in the background, or from within our own app )
// only valid if HelloWorld-Info.plist specifies a protocol to handle
- (BOOL)application:(UIApplication*)application openURL:(NSURL*)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation
{
    if (!url) {
        return NO;
    }
    
    // calls into javascript global function 'handleOpenURL'
    NSString* jsString = [NSString stringWithFormat:@"handleOpenURL(\"%@\");", url];
    [self.viewController.webView stringByEvaluatingJavaScriptFromString:jsString];
    
    // all plugins will get the notification, and their handlers will be called
    [[NSNotificationCenter defaultCenter] postNotification:[NSNotification notificationWithName:CDVPluginHandleOpenURLNotification object:url]];
    
    return YES;
}

// repost all remote and local notification using the default NSNotificationCenter so multiple plugins may respond
- (void)            application:(UIApplication*)application
    didReceiveLocalNotification:(UILocalNotification*)notification
{
    // re-post ( broadcast )
    [[NSNotificationCenter defaultCenter] postNotificationName:CDVLocalNotification object:notification];
}

//- (void)                                application:(UIApplication *)application
//   didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
//{
//    // re-post ( broadcast )
//    NSString* token = [[[[deviceToken description]
//                         stringByReplacingOccurrencesOfString: @"<" withString: @""]
//                        stringByReplacingOccurrencesOfString: @">" withString: @""]
//                       stringByReplacingOccurrencesOfString: @" " withString: @""];
//
//    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotification object:token];
//}
//
//- (void)                                 application:(UIApplication *)application
//    didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
//{
//    // re-post ( broadcast )
//    [[NSNotificationCenter defaultCenter] postNotificationName:CDVRemoteNotificationError object:error];
//}

//- (NSUInteger)application:(UIApplication*)application supportedInterfaceOrientationsForWindow:(UIWindow*)window
//{
//    // iPhone doesn't support upside down by default, while the iPad does.  Override to allow all orientations always, and let the root view controller decide what's allowed (the supported orientations mask gets intersected).
//    NSUInteger supportedInterfaceOrientations = (1 << UIInterfaceOrientationPortrait) | (1 << UIInterfaceOrientationLandscapeLeft) | (1 << UIInterfaceOrientationLandscapeRight) | (1 << UIInterfaceOrientationPortraitUpsideDown);
//    
//    return supportedInterfaceOrientations;
//}

- (void)applicationDidReceiveMemoryWarning:(UIApplication*)application
{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}


@end

@implementation NSURLRequest(DataController)
+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host {
    
    return YES;
}
@end